﻿using System.Runtime.Caching;
namespace WebSocketApi.CacheManager;

/// <summary>
/// 
/// </summary>
public class MemoryCacheService : ICacheContext
{
    /// <summary>
    /// 是否存在此缓存
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public bool Exists(string key)
    {
        return MemoryCache.Default.Contains(key);
    }

    /// <summary>
    /// 取得缓存数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public T GetCache<T>(string key)
    {
        return (T)MemoryCache.Default[key];
    }

    /// <summary>
    /// 设置缓存
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    public bool SetCache<T>(string key, T value)
    {
        try
        {
            MemoryCache.Default.Set(key, value, new CacheItemPolicy
            {
                AbsoluteExpiration = DateTime.Now.AddYears(1)
            });
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    /// <summary>
    /// 设置缓存
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="expire"></param>
    public bool SetCache<T>(string key, T value, DateTime expire)
    {
        try
        {
            MemoryCache.Default.Set(key, value, new CacheItemPolicy
            {
                AbsoluteExpiration = expire
            });
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    /// <summary>
    /// 移除缓存
    /// </summary>
    /// <param name="key"></param>
    public bool Remove(string key)
    {
        try
        {
            MemoryCache.Default.Remove(key);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    /// <summary>
    /// 重命名Key
    /// </summary>
    /// <param name="key"></param>
    /// <param name="newKey"></param>
    /// <returns></returns>
    public bool RenameKey(string key, string newKey)
    {
        try
        {
            MemoryCache.Default[key] = newKey;
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return false;
        }
    }

}
